package com.bluesky.service.impl;

import com.bluesky.common.dto.LoginDTO;
import com.bluesky.common.dto.UserDTO;
import com.bluesky.common.error.ErrorEnum;
import com.bluesky.common.exception.BizException;
import com.bluesky.dao.dataobject.UserPO;
import com.bluesky.dao.mapper.UserMapper;
import com.bluesky.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service

public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public LoginDTO login(LoginDTO loginDTO) {
        //登录实际上就是先查询
        UserPO userPO = userMapper.findUserByName(loginDTO.getName());
        if(Objects.isNull(userPO)){
            return null;
        }
        return new LoginDTO(userPO.getName(),userPO.getId().intValue(),userPO.getPassword());
    }

    @Override
    public void createUser(String name) {
        userMapper.insertUser(name);
    }

    @Override
    public UserDTO queryUserByName(String name) {
        UserPO userPO = userMapper.findUserByName(name);
        //这里用来测试统一异常处理
        //不判断空，看看直接抛出异常的样子
//        if(Objects.isNull(userPO)){
//            return null;
//        }

        //主动捕获异常
        try {
            return new UserDTO(userPO.getName(),userPO.getId().intValue());
        }catch (Exception e){
            throw new BizException(ErrorEnum.DATA_ERROR.getCode(),"根据姓名查询用户可能为空，请检查");
        }

    }

    @Override
    public List<UserDTO> queryAll() {
        List<UserPO> userList = userMapper.findAll();
        if(CollectionUtils.isEmpty(userList)){
            return null;
        }
        return userList.stream()
                .map(u ->new UserDTO(u.getName(),u.getId().intValue()))
                .collect(Collectors.toList());
    }
}
